package cn.com.chengmandian.bike.utils;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.binarywang.wx.miniapp.bean.WxMaUniformMessage;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaRedisConfigImpl;
import cn.com.chengmandian.core.web.pojo.AgentInfo;
import cn.com.chengmandian.core.web.utils.LocalMapUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class WxMiniService {
    private static Map<String, WxMaService> maServices = new HashMap<>();

    @Value("${spring.redis.host}")
    private String redisHost;

    @Value("${spring.redis.port}")
    private Integer redisPort;

    @Value("${spring.redis.password}")
    private String redisPassword;

    public WxMaService getMaServices() {
        AgentInfo agentInfo = LocalMapUtil.getAgentInfo();
        Assert.notNull(agentInfo, "未获取到代理信息");
        Assert.isTrue(StrUtil.isNotBlank(agentInfo.getWxMiniAppid()), "代理未绑定小程序");
        WxMaService wxService = maServices.get(agentInfo.getWxMiniAppid());
        if (wxService == null) {
            return putWxService(agentInfo);
        } else {
            // 如果设置了密钥
            if (StrUtil.isNotEmpty(agentInfo.getWxMiniSecret())) {
                // 之前没设置密钥或者和之前的不一样
                if (StrUtil.isEmpty(wxService.getWxMaConfig().getSecret()) || !wxService.getWxMaConfig().getSecret().equals(agentInfo.getWxMiniSecret())) {
                    return putWxService(agentInfo);
                }
            }
        }
        return wxService;
    }

    private WxMaService putWxService(AgentInfo agentInfo) {
        WxMaDefaultConfigImpl config = new WxMaRedisConfigImpl(new JedisPool(new GenericObjectPoolConfig<>(), redisHost, redisPort, 60, redisPassword));
        config.setAppid(agentInfo.getWxMiniAppid());
        config.setSecret(agentInfo.getWxMiniSecret());
        config.setToken(agentInfo.getWxMiniToken());
        WxMaService wxService = new WxMaServiceImpl();
        wxService.setWxMaConfig(config);
        maServices.put(agentInfo.getWxMiniAppid(), wxService);
        return wxService;
    }

    public void sendMessage(WxMaUniformMessage message) throws WxErrorException {
        WxMaService wxMaService = getMaServices();
        wxMaService.getMsgService().sendUniformMsg(message);
    }

    /**
     * @param wxMaService
     * @param toUser      用户openid
     * @param orderNo     订单号
     * @param rentTime    租车时间
     * @param usedTime    使用时长
     * @param amount      订单金额
     * @throws WxErrorException
     */
    public void sendOrderUnPayMessage(WxMaService wxMaService,String templateId,  String toUser, String orderNo, String rentTime, String usedTime, String amount) throws WxErrorException {
        WxMaSubscribeMessage.MsgData data_orderNo = new WxMaSubscribeMessage.MsgData();
        data_orderNo.setName("character_string12");
        data_orderNo.setValue(orderNo);
        WxMaSubscribeMessage.MsgData data_rentTime = new WxMaSubscribeMessage.MsgData();
        data_rentTime.setName("time13");
        data_rentTime.setValue(rentTime);
        WxMaSubscribeMessage.MsgData data_usedTime = new WxMaSubscribeMessage.MsgData();
        data_usedTime.setName("thing14");
        data_usedTime.setValue(usedTime);
        WxMaSubscribeMessage.MsgData data_amount = new WxMaSubscribeMessage.MsgData();
        data_amount.setName("amount8");
        data_amount.setValue(amount);
        List<WxMaSubscribeMessage.MsgData> dataList = new ArrayList<>();
        dataList.add(data_orderNo);
        dataList.add(data_rentTime);
        dataList.add(data_usedTime);
        dataList.add(data_amount);

        WxMaSubscribeMessage message = WxMaSubscribeMessage.builder()
                .templateId(templateId)
                .page("pagesMy/trip/pay?orderNo=" + orderNo)
                .toUser(toUser)
                .data(dataList).build();
        log.info("发送订单未支付消息:{}", JSONObject.toJSONString(message));

        wxMaService.getSubscribeService().sendSubscribeMsg(message);
    }

    /**
     *  订单工单处理进度通知
     * @param wxMaService
     * @param templateId 通知模板ID
     * @param toUser 用户openId
     * @param billId 骑行订单工单ID
     * @param billNo 工单编号
     * @param status 工单状态
     * @param remark 温馨提示
     * @throws WxErrorException
     */
    public void sendOrderBillMessage(WxMaService wxMaService, String templateId,  String toUser, Integer billId, String billNo, String title, String content, String status, String remark) throws WxErrorException {
        WxMaSubscribeMessage.MsgData data_bill_no = new WxMaSubscribeMessage.MsgData();
        data_bill_no.setName("character_string1");
        data_bill_no.setValue(billNo);

        WxMaSubscribeMessage.MsgData data_status = new WxMaSubscribeMessage.MsgData();
        data_status.setName("phrase2");
        data_status.setValue(status);

        WxMaSubscribeMessage.MsgData data_remark = new WxMaSubscribeMessage.MsgData();
        data_remark.setName("thing3");
        data_remark.setValue(remark);

        WxMaSubscribeMessage.MsgData data_time = new WxMaSubscribeMessage.MsgData();
        data_time.setName("time4");
        data_time.setValue(DateUtil.date().toString("yyyy-MM-dd HH:mm:ss"));

        List<WxMaSubscribeMessage.MsgData> dataList = new ArrayList<>();
        dataList.add(data_bill_no);
        dataList.add(data_status);
        dataList.add(data_remark);
        dataList.add(data_time);

        WxMaSubscribeMessage message = WxMaSubscribeMessage.builder()
                .templateId(templateId)
                .page("pagesMy/serviceRecordDetails/serviceRecordDetails?type=3&id=" + billId + "&title=" + title + "&content=" + content)
                .toUser(toUser)
                .data(dataList).build();
        log.info("订单工单处理进度通知:{}", JSONObject.toJSONString(message));

        wxMaService.getSubscribeService().sendSubscribeMsg(message);
    }
}
